package com.xrui.hbasecmd.io;

import com.xrui.hbase.util.ResourceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;

public class Downloader {
    //region Constants
    private final static Logger LOG = LoggerFactory.getLogger(Downloader.class);
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    //endregion

    //region Constructor
    private Downloader() {
    }
    //endregion

    //region Public Methods
    public static File download(URL url) throws IOException {
        LOG.debug("Downloading {}...", url);
        StringBuilder fileName = new StringBuilder();
        StringBuilder extension = new StringBuilder();

        extractFileNameAndExtension(url.getPath(), fileName, extension);

        File temp = File.createTempFile(fileName.toString() + '-', extension.length() == 0 ? null : extension.toString());

        InputStream in = url.openStream();
        OutputStream out = new FileOutputStream(temp);

        try {
            copy(in, out);
            LOG.debug("{} downloaded to {}", url, temp);
        } finally {
            ResourceUtils.closeOrLog(in);
            ResourceUtils.closeOrLog(out);
        }

        return temp;
    }
    //endregion

    //region Private Methods
    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];

        int bytesRead;

        while (-1 != (bytesRead = in.read(buffer))) {
            out.write(buffer, 0, bytesRead);
        }
    }

    private static void extractFileNameAndExtension(String path, StringBuilder fileName, StringBuilder extension) {
        String leaf = path.replace("\\", "/");

        int index = leaf.lastIndexOf('/');
        if (index != -1) {
            leaf = leaf.substring(index + 1);
        }

        index = leaf.lastIndexOf('.');
        if (index == -1) {
            fileName.append(leaf);
        } else {
            fileName.append(leaf.substring(0, index));
            extension.append(leaf.substring(index));
        }
    }
    //endregion
}
